#pragma once

#include <iostream>
using namespace std;
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<functional>





namespace Server
{
    static const string defaultip = "0.0.0.0";
    //函数模板（参数是string，string，string）
    typedef function<void (int,string,int,string)> func_t;

    class udpServer
    {
    public:
        udpServer(const func_t& func,const uint16_t &port, const string &ip = defaultip) : _callback(func),_port(port), _ip(ip), _sockfd(-1)
        {
        }

        void initServer()
        {
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                perror("socket errno\n");
                exit(2);
            }

            struct sockaddr_in ret;
            bzero(&ret, sizeof(ret));
            ret.sin_family = AF_INET;
            ret.sin_port = htons(_port);
            ret.sin_addr.s_addr = INADDR_ANY;

            int n = bind(_sockfd, (sockaddr *)&ret, sizeof(ret));
            if (n == -1)
            {
                perror("bind errno\n");
                exit(3);
            }
            cout << "socket bind success" << endl;
        }

        void start()
        {
            char buffer[1024];
            while (1)
            {
                struct sockaddr_in ret;
                socklen_t len = sizeof(ret);
                //输出型参数，recvform，
                size_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (sockaddr *)&ret, &len);
                if (s > 0)
                {
                    buffer[s] = 0;
                    //把int的ip转换为点分式，并且完成网络序列号切换
                    string Client_ip = inet_ntoa(ret.sin_addr);
                    uint16_t Client_port = ntohs(ret.sin_port);
                    cout << Client_ip << "[" << Client_port << "]#" << buffer << endl;

                    //我们不仅要把数据读取上来，还要对数据进行处理
                    //这里的处理就是翻译客户端输入的数据
                    _callback(_sockfd,Client_ip,Client_port,buffer);//回调
                }
                sleep(1);
            }
        }

        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;

        func_t _callback;//回调函数
    };
}